<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script setup lang="ts">
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '/@/views/system/menu/data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';

  import { addMenu, getMenuTree, updateMenu } from '/@/api/sys/menu';
  import { removeButton, transformTreeData } from '/@/utils/helper/transformTreeData';
  const isUpdate = ref(true);
  const menu_id = ref(null);
  const emits = defineEmits(['register', 'success']);

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    await setFieldsValue({
      type: 0,
    });
    if (unref(isUpdate)) {
      await setFieldsValue({
        ...data.record,
      });
      menu_id.value = data.record.id;
    }

    let treeData = await getMenuTree();
    let lst = removeButton(treeData);
    transformTreeData(lst, isUpdate, data);
    await updateSchema({
      field: 'parent_id',
      componentProps: { treeData: lst },
    });
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      if (unref(isUpdate)) {
        values['id'] = menu_id.value;
        await updateMenu(values);
      } else {
        await addMenu(values);
      }
      emits('success');
      closeDrawer();
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<style scoped lang="less"></style>
